package com.moli.iov.util.api;


import com.moli.iov.util.api.enums.SignTypeEnum;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * <p>
 *  验签工具
 * </p>
 *
 * @author zql
 * @since 2019/8/12 11:38
 */
public class ApiUtils {

    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static final String SYMBOLS_LOWER = "0a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y6z";

    private static final Random RANDOM = new SecureRandom();

    private static final String SHA = "HmacSHA256";

    private static final String MD5 = "MD5";

    /**
     * 获取小写随机字符串 Nonce Str
     *
     * @param length 长度
     * @return String 随机字符串
     */
    public static String generateNonceStrLower(int length){
        return generateNonceStr(length, SYMBOLS_LOWER);
    }


    /**
     * 获取随机字符串 Nonce Str
     *
     * @return String 随机字符串
     */
    public static String generateNonceStr() {
        return generateNonceStr(32, SYMBOLS);
    }

    /**
     * 获取随机字符串 Nonce Str
     *
     * @param length 长度
     * @return String 随机字符串
     */
    public static String generateNonceStr(int length, String symbols){
        char[] nonceChars = new char[length];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = symbols.charAt(RANDOM.nextInt(symbols.length()));
        }
        return new String(nonceChars);
    }

    /**
     * 判断签名是否正确，必须包含sign字段，否则返回false。
     *
     * @param data Map类型数据
     * @param key API密钥
     * @param signType 签名方式
     * @return 签名是否正确
     * @throws Exception
     */
    public static boolean isSignatureValid(Map<String, Object> data, String key, SignTypeEnum signType) throws Exception {
        if (!data.containsKey(ApiConstants.FIELD_SIGN) ) {
            return false;
        }
        Map<String, String> map= formatMap(data);
        String sign = map.get(ApiConstants.FIELD_SIGN);
        return generateSignature(map, key, signType).equals(sign);
    }


    /**
     * 生成签名
     *
     * @param data 待签名数据
     * @param key API密钥
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data, String key) throws Exception {
        return generateSignature(data, key, SignTypeEnum.MD5);
    }

    /**
     * 生成签名
     *
     * @param data 待签名数据
     * @param key API密钥
     * @param signType 签名方式
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data, String key, SignTypeEnum signType) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals(ApiConstants.FIELD_SIGN)) {
                continue;
            }
            if (data.get(k).trim().length() > 0){
                // 参数值为空，则不参与签名
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
            }
        }
        sb.append("key=").append(key);
        if (SignTypeEnum.MD5.equals(signType)) {
            return MD5(sb.toString()).toUpperCase();
        } else if (SignTypeEnum.HMACSHA256.equals(signType)) {
            return HMACSHA256(sb.toString(), key);
        } else {
            throw new Exception(String.format("Invalid sign_type: %s", signType));
        }
    }

    /**
     * 生成 MD5
     *
     * @param data 待处理数据
     * @return MD5结果
     */
    public static String MD5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance(MD5);
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

    /**
     * 生成 HMACSHA256
     * @param data 待处理数据
     * @param key 密钥
     * @return 加密结果
     * @throws Exception
     */
    public static String HMACSHA256(String data, String key) throws Exception {
        Mac sha256_HMAC = Mac.getInstance(SHA);
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), SHA);
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

    /**
     * 泛型转换
     * @param data
     * @return
     */
    public static Map<String, String> formatMap(Map<String, Object> data){

        Map<String, String> map= new HashMap<>();
        data.forEach((k, v) -> {
            map.put(k, String.valueOf(v));
        });

        return map;
    }
}
